from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework.response import Response


class ImageCodeSerializer(serializers.Serializer):
    text = serializers.CharField(max_length=4,min_length=4,label="图片验证码")
    image_code_id = serializers.CharField(label="图片验证码在redis中的编号")

    #多字段校验
    def validate(self, attrs):
        #获取可选参数
        text = attrs["text"]
        image_code_id = attrs["image_code_id"]

        #获取redis中的图片验证码,有可能已经过期了
        redis_conn = get_redis_connection("code")

        #如果过期了则报错
        redis_text = redis_conn.get("image_code_%s"%image_code_id)
        if not redis_conn.get("image_code_%s"%image_code_id):
            raise serializers.ValidationError("验证码已过期")

        #删除图像验证码
        redis_conn.delete("image_code_%s"%image_code_id)

        #校验是不是一样
        if text.upper() != redis_text.decode().upper():
            raise serializers.ValidationError("图像验证码错误")

        return attrs

        pass
    pass